package com.aviccxzx.smarthome.UserModule;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;

import com.aviccxzx.smarthome.Colorplate.ColorSelectDialog;
import com.aviccxzx.smarthome.DeviceModule.GosDeviceModuleBaseActivity;
import com.aviccxzx.smarthome.MsgID;
import com.aviccxzx.smarthome.R;
import com.aviccxzx.smarthome.entity.FeedBack;
import com.aviccxzx.smarthome.entity.UnbundBean;
import com.aviccxzx.smarthome.fragment.DeviceListFragment;
import com.aviccxzx.smarthome.netutil.app.App;
import com.aviccxzx.smarthome.service.RetrofitHelper;
import com.aviccxzx.smarthome.service.RetrofitService;
import com.aviccxzx.smarthome.utils.ChangeNameDialogUtil;
import com.aviccxzx.smarthome.utils.DensityUtil;
import com.aviccxzx.smarthome.utils.DialogUtil;
import com.aviccxzx.smarthome.view.ListViewAdaptWidth;
import com.aviccxzx.smarthome.view.TextMoveLayout;
import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.gizwits.gizwifisdk.api.GizWifiSDK;
import com.gizwits.gizwifisdk.enumration.GizDeviceSharingUserRole;
import com.gizwits.gizwifisdk.enumration.GizWifiDeviceNetStatus;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.gizwits.gizwifisdk.listener.GizWifiDeviceListener;
import com.google.gson.Gson;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import cn.jpush.android.api.JPushInterface;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.aviccxzx.smarthome.fragment.DeviceListFragment.isFromDeviceList;
import static com.aviccxzx.smarthome.fragment.DeviceListFragment.mDevice;
import static com.aviccxzx.smarthome.fragment.DeviceListFragment.mGprsDevice;
import static com.aviccxzx.smarthome.fragment.DeviceListFragment.myDeviceList;
import static com.aviccxzx.smarthome.fragment.DeviceListFragment.subList;
import static com.gizwits.gizwifisdk.enumration.GizWifiDeviceNetStatus.GizDeviceControlled;


/**
 * Created by joey on 201610/10.
 */
public class GatewaySetActivity extends GosDeviceModuleBaseActivity implements View.OnClickListener {

    private SeekBar mSeekbar = null;
    private SeekBar mSeekbar_rate = null;
    private SeekBar mSeekbar_screen = null;
    private TextView moveText;

    private int screenWidth;//屏幕宽度
    private TextMoveLayout textMoveLayout;

    private TextView mTvMax;
    private TextView gateway_name_tv, gateway_icid;

    private LinearLayout mParentView, ll_parent_rate, ll_iccid;

    private ColorSelectDialog colorSelectDialog;
    private int lastColor, red, green, blue;
    private ImageView color_choosed_iv, gateset_img;
    private TextView lightrate_tv, now_time_tv, battery_tv, zigbee_state_tv, wifistate_tv, gateway_mac, gate_version;

    List<String> listmenu;
    private PopupWindow popupWindow;
    private ArrayAdapter<String> adapter;

    private Window window;
    String uid = "";
    String mac = "";
    String imei = "";
    String token;


    int lampFrequency;
    int LampBrightness;
    String gateVersion;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setContentView(R.layout.gateway_set_lay_v19);
        } else {

            //            setContentView( R.layout.gateway_set_lay);
        }
        ((TextView) findViewById(R.id.title_tv)).setText("智能网关设置");
        setControl();
        initView();
        click();
    }

    Boolean powersupply;
    int battery;
    Boolean zig, wifistate;
    /**
     * 获取上报的网关电量
     */
    private GizWifiDeviceListener deviceListener = new GizWifiDeviceListener() {
        @Override
        public void didReceiveData(GizWifiErrorCode result, GizWifiDevice device, ConcurrentHashMap<String, Object> dataMap, int sn) {
            super.didReceiveData(result, device, dataMap, sn);
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                if (dataMap.get("data") != null) {
                    ConcurrentHashMap<String, Object> map = (ConcurrentHashMap<String, Object>) dataMap.get("data");
                    /*// 扩展数据点，key为"kuozhan"
                    //网关的电量上报
                    int battery = (int) map.get("Battery");
                    battery_tv.setText(battery + "%");
                    Boolean zig = (Boolean) map.get("Zigbee_State");
                    Boolean wifistate = (Boolean) map.get("WiFi_State");
                    if (zig) {
                        zigbee_state_tv.setText("良好");
                    } else {
                        zigbee_state_tv.setText("断开");
                    }
                    if (wifistate) {
                        wifistate_tv.setText("良好");
                    } else {
                        wifistate_tv.setText("断开");
                    }*/

                    if (map.get("PowerSupplyMode") != null) {
                        powersupply = (Boolean) map.get("PowerSupplyMode");
                    }
                    byte[] hard = (byte[]) map.get("MCU_version_number");
                    String version = bytesToHex(hard).toString().replace(" ", "");
                    String code = version.substring(1, 2);

                    if (code.equals("1")) {
                        gateVersion = "SH-WG1-001";
                    } else if (code.equals("4")) {
                        gateVersion = "SH-WG1-004";
                    } else if (code.equals("2")) {
                        gateVersion = "SH-WG1-002";
                    } else if (code.equals("3")) {
                        gateVersion = "SH-WG1-003";
                    }
                    gate_version.setText(gateVersion);
                    if (map.get("LampFrequency") != null) {
                        lampFrequency = (int) map.get("LampFrequency");
                        rateProgress = lampFrequency;
                    }
                    if (map.get("LampBrightness") != null) {
                        LampBrightness = (int) map.get("LampBrightness");
                        brightnessProgress = LampBrightness;
                    }

                    new SeekBarUtil(mSeekbar, mParentView, mTvMax, screenWidth, GatewaySetActivity.this, textMoveLayout);
                    new SeekBarUtil_rate(mSeekbar_rate, ll_parent_rate, mTvMax, screenWidth, GatewaySetActivity.this, textMoveLayout);

                    if (powersupply) {
                        battery_tv.setText("插电");
                    } else {
                        if (map.get("Battery") != null) {
                            battery = (int) map.get("Battery");
                        }
                        spf.edit().putString("Battery", battery + "");
                        battery_tv.setText(battery + "%");
                    }
                    if (mGprsDevice != null) {
                        //如果有gprs
                        if (map.get("ICCID") != null) {
                            byte[] iccid = (byte[]) map.get("ICCID");
                            String icd = bytesToHex(iccid).toString().replace(" ", "");
                                char[] chars = icd.toCharArray();
                                StringBuffer sb = new StringBuffer();
                                for (int i = 1; i < chars.length; i += 2) {
                                    sb.append(chars[i]);
                                }
                                icd = sb.toString();
                                ll_iccid.setVisibility(View.VISIBLE);
                                gateway_icid.setText(icd);
                        }
                    }else {
                        ll_iccid.setVisibility(View.GONE);
                    }

                    if (map.get("Zigbee_State") != null) {
                        zig = (Boolean) map.get("Zigbee_State");
                    }
                    if (map.get("WiFi_State") != null) {
                        wifistate = (Boolean) map.get("WiFi_State");
                    }
                    if (zig) {
                        zigbee_state_tv.setText("正常");
                    } else {
                        zigbee_state_tv.setText("断开");
                    }
                    //                        if (mGprsDevice == null) {
                    if (wifistate) {
                        wifistate_tv.setText("正常");
                    } else {
                        wifistate_tv.setText("断开");
                    }
                    if (map.get("Red") != null && map.get("Green") != null && map.get("Blue") != null) {
                        red = (int) map.get("Red");
                        green = (int) map.get("Green");
                        blue = (int) map.get("Blue");
                        int getcolor = Color.argb(255, red, green, blue);
                        color_choosed_iv.setBackgroundColor(getcolor);
                    }
                }
            }
        }
    };

    private void setControl() {
        if (mDevice != null) {
            mDevice.setSubscribe(MsgID.PS, true);
            mDevice.setListener(subListener);
        }
    }

    /**
     * 订阅实现回调
     */
    GizWifiDeviceListener subListener = new GizWifiDeviceListener() {
        @Override
        public void didSetSubscribe(GizWifiErrorCode result, GizWifiDevice
                device, boolean isSubscribed) {
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                // 订阅或解除订阅成功
                mDevice.setListener(deviceListener);
                mDevice.getDeviceStatus(null);
            } else {
            }
        }
    };

    final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();

    // 将16进制的byte转为string，比如byte值为{0x62,0x63}，那么将转为“6263”
    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 3];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 3] = hexArray[v >>> 4];
            hexChars[j * 3 + 1] = hexArray[v & 0x0F];
            hexChars[j * 3 + 2] = ' ';
        }
        return new String(hexChars);
    }

    boolean controlled = false;

    @Override
    protected void didUpdateNetStatus(GizWifiDevice device, GizWifiDeviceNetStatus netStatus) {
        super.didUpdateNetStatus(device, netStatus);
        if (netStatus == GizDeviceControlled) {
            controlled = true;
        }
    }


    private void click() {
        findViewById(R.id.ll_title_left_view).setOnClickListener(this);
        findViewById(R.id.choose_color).setOnClickListener(this);
        findViewById(R.id.change_name_ll).setOnClickListener(this);
        findViewById(R.id.delete_gateway_tv).setOnClickListener(this);
        //        findViewById(R.id.set_lightrate).setOnClickListener(this);
    }

    private void initView() {
        uid = spf.getString("Uid", "");
        mac = spf.getString("gatemac", "");
        imei = spf.getString("Imei", "");
        token = spf.getString("Token", "");
        String name = getIntent().getStringExtra("name");
        //        int color = getIntent().getIntExtra("color", 0);
        String zigbee = getIntent().getStringExtra("zigbee");
        String wifi = getIntent().getStringExtra("wifi");
        //        String battery = getIntent().getStringExtra("battery");
        //        lampFrequency = getIntent().getIntExtra("lampFrequency", 0);
        //        LampBrightness = getIntent().getIntExtra("LampBrightness", 0);
        //        gateVersion = getIntent().getStringExtra("gateVersion");
        gateset_img = (ImageView) findViewById(R.id.gateset_img);
        gate_version = (TextView) findViewById(R.id.gate_version);
        color_choosed_iv = (ImageView) findViewById(R.id.color_choosed_iv);
        //        gate_version.setText(gateVersion);
        //        if (color != 0) {
        //            color_choosed_iv.setBackgroundColor(color);
        //        }
        gateway_name_tv = (TextView) findViewById(R.id.gateway_name_tv);
        if (!TextUtils.isEmpty(name)) {
            gateway_name_tv.setText(name);
        } else {
            gateway_name_tv.setText("智能网关");
        }
        ll_iccid = (LinearLayout) findViewById(R.id.ll_iccid);
        gateway_icid = (TextView) findViewById(R.id.gateway_icid);

        TextView title_right_text = (TextView) findViewById(R.id.title_right_text);
        title_right_text.setVisibility(View.VISIBLE);
        title_right_text.setText("保存");
        title_right_text.setOnClickListener(this);

        battery_tv = (TextView) findViewById(R.id.battery_tv);
        zigbee_state_tv = (TextView) findViewById(R.id.zigbee_state_tv);
        wifistate_tv = (TextView) findViewById(R.id.wifistate_tv);

        zigbee_state_tv.setText(zigbee);
        //        battery_tv.setText(battery);
        wifistate_tv.setText(wifi);

        now_time_tv = (TextView) findViewById(R.id.now_time_tv);
        lightrate_tv = (TextView) findViewById(R.id.lightrate_tv);
        gateway_mac = (TextView) findViewById(R.id.gateway_mac);

        gateway_mac.setText(mDevice.getMacAddress());

        screenWidth = getWindowManager().getDefaultDisplay().getWidth();
        mSeekbar = (SeekBar) findViewById(R.id.seekbar);
        mParentView = (LinearLayout) findViewById(R.id.ll_parent);
        mTvMax = (TextView) findViewById(R.id.tv_max);
        textMoveLayout = (TextMoveLayout) findViewById(R.id.textLayout);
        //        new SeekBarUtil(mSeekbar, mParentView, mTvMax, screenWidth, GatewaySetActivity.this, textMoveLayout);

        mSeekbar_rate = (SeekBar) findViewById(R.id.seekbar_rate);
        ll_parent_rate = (LinearLayout) findViewById(R.id.ll_parent_rate);
        //        new SeekBarUtil_rate(mSeekbar_rate, ll_parent_rate, mTvMax, screenWidth, GatewaySetActivity.this, textMoveLayout);

        if (mDevice.getNetStatus() == GizWifiDeviceNetStatus.GizDeviceOffline) {
            //网关没上电 把网关图片虚化
            gateset_img.setBackgroundResource(R.mipmap.gateway_pic_offline);
        } else {
            gateset_img.setBackgroundResource(R.mipmap.gateway_pic);
        }
        listmenu = new ArrayList<>();
        for (int a = 1; a < 11; a++) {
            listmenu.add(a + "");
        }
        getTime();
    }

    public void getTime() {
        String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());
        now_time_tv.setText(datetime);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_title_left_view:
                finish();
                break;
            case R.id.title_right_text:
                //保存按钮时发送相关的设置
                ConcurrentHashMap<String, Object> dataMap = new ConcurrentHashMap<>();
                dataMap.put("Red", red);
                dataMap.put("Green", green);
                dataMap.put("Blue", blue);
                dataMap.put("LampBrightness", brightnessProgress);
                dataMap.put("LampFrequency", rateProgress);
                mDevice.write(dataMap, 0);
                App.getApp().showToast("保存成功");
                break;
            case R.id.set_lightrate:
                //选择呼吸灯的频率
                if (popupWindow == null) {
                    View contentView = LayoutInflater.from(GatewaySetActivity.this).inflate(R.layout.popurwindow, null);
                    ListViewAdaptWidth listViewAdaptWidth = (ListViewAdaptWidth) contentView.findViewById(R.id.listView);
                    adapter = new ArrayAdapter<>(GatewaySetActivity.this, R.layout.item, R.id.txtView_pop, listmenu);
                    listViewAdaptWidth.setAdapter(adapter);
                    listViewAdaptWidth.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            lightrate_tv.setText((i + 1) + "");
                            popupWindow.dismiss();
                        }
                    });
                    popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
                }

                window = GatewaySetActivity.this.getWindow();
                popupWindow.setBackgroundDrawable(new ColorDrawable());
                popupWindow.setOutsideTouchable(true);

                popupWindow.setFocusable(true);
                popupWindow.update();
                backgroundAlpha(0.5f);
                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        backgroundAlpha(1.0f);
                    }
                });

                int[] position = new int[2];
                view.getLocationOnScreen(position);
                int y = position[1] + view.getMeasuredHeight();
                popupWindow.showAtLocation(lightrate_tv, Gravity.CENTER, 0, 0);
                break;
            case R.id.delete_gateway_tv:
                new DialogUtil(GatewaySetActivity.this, true, true, "确认删除网关", "取消", "确定", new DialogUtil.SureInterfance() {
                    @Override
                    public void sureTodo() {
                        if (subList.size() > 0 || myDeviceList.size() > 0) {
                            //子设备删除成功后才可以进行删除网关的操作
                            App.getApp().showToast("请先删除所有子设备再删除网关！");
                        } else {
                            if (mDevice.getSharingRole() == GizDeviceSharingUserRole.GizDeviceSharingOwner || mDevice.getSharingRole() == GizDeviceSharingUserRole.GizDeviceSharingSpecial) {
                                unBund(1);
                            } else {
                                unBund(0);
                            }
                        }
                    }

                    @Override
                    public void cancle() {

                    }
                }).showCustomDialog();
                break;
            case R.id.change_name_ll:
                changeName();
                break;
            case R.id.choose_color:
                if (colorSelectDialog == null) {
                    colorSelectDialog = new ColorSelectDialog(GatewaySetActivity.this);
                    colorSelectDialog.setOnColorSelectListener(new ColorSelectDialog.OnColorSelectListener() {
                        @Override
                        public void onSelectFinish(int color) {
                            color_choosed_iv.setBackground(new ColorDrawable(color));
                            spf.edit().putInt("colorselected", color).commit();
                            red = Color.red(color);
                            green = Color.green(color);
                            blue = Color.blue(color);
                        }
                    });
                }
                //                colorSelectDialog.setLastColor(lastColor);
                colorSelectDialog.show();
                break;
        }
    }

    public void unBund(int admin) {
        progressDialog.show();
        RetrofitService service = RetrofitHelper.getInstance(this).getServer();
        Gson gson = new Gson();
        List<String> childMac = new ArrayList<>();
        List<String> shareMac = new ArrayList<>();
        for (GizWifiDevice device : subList) {
            if (device.getSharingRole() != null && device.getSharingRole().equals(GizDeviceSharingUserRole.GizDeviceSharingGuest)) {
                //分享的子设备
                shareMac.add(device.getMacAddress().toUpperCase());
            } else {
                childMac.add(device.getMacAddress().toUpperCase());
            }
        }
        /**
         * {
         "admin": 0,
         "appId": "string",
         "childMac": [
         "string"
         ],
         "frontDto": {
         "imei": "string",
         "mac": "string",
         "uid": "string"
         },
         "shareMac": [
         "string"
         ],
         "token": "string"
         }
         */
        UnbundBean unbund = new UnbundBean();
        unbund.setAdmin(admin);
        unbund.setAppId(MsgID.APP_ID);
        unbund.setChildMac(childMac);

        UnbundBean.FrontDtoBean bean = new UnbundBean.FrontDtoBean();
        bean.setImei(imei);
        bean.setMac(mac);
        bean.setUid(uid);

        unbund.setFrontDto(bean);
        unbund.setShareMac(shareMac);
        unbund.setToken(token);

        String strEntity = gson.toJson(unbund);

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), strEntity);
        Call<FeedBack> call = service.unbund(body);
        call.enqueue(new Callback<FeedBack>() {
            @Override
            public void onResponse(Call<FeedBack> call, Response<FeedBack> response) {
                if (response.body() != null) {
                    int code = response.body().getCode();
                    if (code == 4) {
                        //场景删除成功 然后开始解绑设备相关
                        /*for (GizWifiDevice device : subList) {
                            GizWifiSDK.sharedInstance().unbindDevice(uid, token, device.getDid());
                        }*/
                        if (mDevice.getAlias().equals("GPRS_网关")) {
                            //GPRS版本的网关，需要先解绑网关版本的网关
                            GizWifiSDK.sharedInstance().unbindDevice(uid, token, spf.getString("wifidid", ""));
                        }
                        GizWifiSDK.sharedInstance().unbindDevice(uid, token, mDevice.getDid());
                    } else {
                        /*for (GizWifiDevice device : subList) {
                            GizWifiSDK.sharedInstance().unbindDevice(uid, token, device.getDid());
                        }*/
                        if (mDevice.getAlias().equals("GPRS_网关")) {
                            //GPRS版本的网关，需要先解绑网关版本的网关
                            GizWifiSDK.sharedInstance().unbindDevice(uid, token, spf.getString("wifidid", ""));
                        }
                        GizWifiSDK.sharedInstance().unbindDevice(uid, token, mDevice.getDid());
                    }
                } else {
                    /*for (GizWifiDevice device : subList) {
                        GizWifiSDK.sharedInstance().unbindDevice(uid, token, device.getDid());
                    }*/
                    if (mDevice.getAlias().equals("GPRS_网关")) {
                        //GPRS版本的网关，需要先解绑网关版本的网关
                        GizWifiSDK.sharedInstance().unbindDevice(uid, token, spf.getString("wifidid", ""));
                    }
                    GizWifiSDK.sharedInstance().unbindDevice(uid, token, mDevice.getDid());
                }
            }

            @Override
            public void onFailure(Call<FeedBack> call, Throwable t) {

            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        int colorselected = spf.getInt("colorselected", 0);
        if (colorselected != 0) {
            color_choosed_iv.setBackground(new ColorDrawable(colorselected));
        }
    }

    /**
     * 设备取消订阅回调
     *
     * @param result
     * @param did
     */
    @Override
    protected void didUnbindDevice(GizWifiErrorCode result, String did) {
        progressDialog.dismiss();
        super.didUnbindDevice(result, did);
        if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
            //确保网关解绑成功了 则所有的子设备都解绑成功了
            if (did.equals(mDevice.getDid())) {
                //                tagSet.clear();
                //                tagSet.add(uid);
                //                JPushInterface.setTags(GatewaySetActivity.this, 0, tagSet);
                JPushInterface.stopPush(getApplicationContext());
                spf.edit().putString("onekey", "").commit();//删除在家离家模式
                //删除短信和推送标志
                spf.edit().putString("msgSwitch", "").commit();
                spf.edit().putBoolean("tagset", true).commit();
                spf.edit().putString("addMac", "").commit();
                spf.edit().putBoolean("tagset", true).commit();
                spf.edit().putString("Imei", "").commit();
                DeviceListFragment.hasGateWay = false;
                isFromDeviceList = false;
                finish();
            }
        } else {
            App.getApp().showToast("删除失败，请稍候再试");
        }
    }

    String gateName = "";

    private void changeName() {
        new ChangeNameDialogUtil(GatewaySetActivity.this, "修改网关名称", new ChangeNameDialogUtil.SureInterfance() {
            @Override
            public void sureTodo(String name) {
                //确定修改 处理方案
                App.getApp().showToast(name);
                deviceslist = GizWifiSDK.sharedInstance().getDeviceList();
                gateName = name;
                mDevice.setListener(getGizWifiDeviceListener());
                mDevice.setCustomInfo("", name);
                progressDialog.show();
            }
        }).showSelfDialog();
    }

    /**
     * 修改名字回调
     *
     * @param result 错误码
     * @param device 当前设备
     */
    @Override
    public void didSetCustomInfo(GizWifiErrorCode result, GizWifiDevice device) {
        super.didSetCustomInfo(result, device);
        progressDialog.dismiss();
        if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
            // 修改成功
            App.getApp().showToast("修改成功");
            gateway_name_tv.setText(gateName);
            //                finish();
        } else {
            //修改失败
            App.getApp().showToast("修改失败");
        }
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {

        WindowManager.LayoutParams lp = window.getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        window.setAttributes(lp);
    }

    int brightnessProgress;//呼吸灯亮度值

    public class SeekBarUtil {
        private SeekBar mSeekbar = null;
        private TextView moveText;

        private int screenWidth;//屏幕宽度
        private ViewGroup.LayoutParams layoutParams;

        private int mLeftMargin;
        private TextPaint mPaint;
        private TextView mTvMax;
        private LinearLayout mParentView;
        private Boolean firstIn = false;
        private TextMoveLayout textMoveLayout;
        private Context mContext;

        public SeekBarUtil(SeekBar mSeekbar, LinearLayout mParentView, TextView mTvMax, int screenWidth, Context mContext, TextMoveLayout textMoveLayout) {
            this.mSeekbar = mSeekbar;
            this.mParentView = mParentView;
            this.mTvMax = mTvMax;
            this.screenWidth = screenWidth;
            this.mContext = mContext;
            this.textMoveLayout = textMoveLayout;
            firstIn = true;
            setMoveTextView();
            getChildenLayoutParams();
            setSeekBarValues();
        }


        /**
         * 设置moveTextView的基础参数
         */
        private void setMoveTextView() {

            moveText = new TextView(mContext);
            moveText.setText(0 + "");
            moveText.setTextColor(Color.rgb(0, 161, 229));
            moveText.setTextSize(16);

            layoutParams = new ViewGroup.LayoutParams(screenWidth, 50);

            textMoveLayout.addView(moveText, layoutParams);
            moveText.layout(5, 20, screenWidth, 80);
        }

        /**
         * 获取子view的marginLayoutParams
         */
        private void getChildenLayoutParams() {
            View childAt = mParentView.getChildAt(0);
            ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) childAt.getLayoutParams();
            mLeftMargin = marginLayoutParams.leftMargin;
            mSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListenerImp());
        }

        /**
         * 设置seekbar的基础参数
         */
        public void setSeekBarValues() {

            //        mTvMax.setText("100");
            mSeekbar.setEnabled(true);
            mSeekbar.setMax(100);
            if (LampBrightness != 0) {
                mSeekbar.setProgress(LampBrightness);
                mTvMax.setText(LampBrightness + "");
            } else {
                mSeekbar.setProgress(50);
                mTvMax.setText(LampBrightness + "");
            }
        }

        /**
         * seekbar滑动监听
         */
        private class OnSeekBarChangeListenerImp implements
                SeekBar.OnSeekBarChangeListener {

            // 触发操作，拖动
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                setMoveTextLayout();
            }

            // 开始拖动时候触发的操作
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            // 停止拖动时候
            public void onStopTrackingTouch(SeekBar seekBar) {
                brightnessProgress = seekBar.getProgress();
                //                ConcurrentHashMap<String, Object> dataMap = new ConcurrentHashMap<>();
                //                dataMap.put("LampBrightness", progress);
                //                mDevice.write(dataMap, 0);
            }
        }

        /**
         * seekbar滑动过程中改变moveTextView的位置
         */
        private void setMoveTextLayout() {
            if (mPaint == null) {
                mPaint = new TextPaint();
            }

            float measureText = mPaint.measureText(moveText.getText().toString().trim());
            Rect bounds = mSeekbar.getProgressDrawable().getBounds();
            int xFloat = (int) (bounds.width() * mSeekbar.getProgress() / mSeekbar.getMax() - measureText / 2 + DensityUtil.px2dip(mContext, mLeftMargin));
            if (firstIn) {
                firstIn = false;
                moveText.layout(624, 20, screenWidth, 80);
                moveText.setText(100 + "");
                mTvMax.setText(100 + "");
            } else {
                moveText.layout(xFloat, 20, screenWidth, 80);
                moveText.setText(mSeekbar.getProgress() + "");
                mTvMax.setText(mSeekbar.getProgress() + "");
            }

        }
    }

    int rateProgress;//呼吸灯频率值

    public class SeekBarUtil_rate {
        private SeekBar mSeekbar = null;
        private TextView moveText;

        private int screenWidth;//屏幕宽度
        private ViewGroup.LayoutParams layoutParams;

        private int mLeftMargin;
        private TextPaint mPaint;
        private TextView mTvMax;
        private LinearLayout mParentView;
        private Boolean firstIn = false;
        private TextMoveLayout textMoveLayout;
        private Context mContext;

        public SeekBarUtil_rate(SeekBar mSeekbar, LinearLayout mParentView, TextView mTvMax, int screenWidth, Context mContext, TextMoveLayout textMoveLayout) {
            this.mSeekbar = mSeekbar;
            this.mParentView = mParentView;
            this.mTvMax = mTvMax;
            this.screenWidth = screenWidth;
            this.mContext = mContext;
            this.textMoveLayout = textMoveLayout;
            firstIn = true;
            //            setMoveTextView();
            getChildenLayoutParams();
            setSeekBarValues();
        }


        /**
         * 设置moveTextView的基础参数
         */
        private void setMoveTextView() {

            moveText = new TextView(mContext);
            moveText.setText(0 + "");
            moveText.setTextColor(Color.rgb(0, 161, 229));
            moveText.setTextSize(16);

            layoutParams = new ViewGroup.LayoutParams(screenWidth, 50);

            //        textMoveLayout = (TextMoveLayout) findViewById(R.id.textLayout);

            textMoveLayout.addView(moveText, layoutParams);
            moveText.layout(5, 20, screenWidth, 80);
        }

        /**
         * 获取子view的marginLayoutParams
         */
        private void getChildenLayoutParams() {
            View childAt = mParentView.getChildAt(0);
            ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) childAt.getLayoutParams();
            mLeftMargin = marginLayoutParams.leftMargin;
            mSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListenerImp());
        }

        /**
         * 设置seekbar的基础参数
         */
        public void setSeekBarValues() {

            //        mTvMax.setText("100");
            mSeekbar.setEnabled(true);
            mSeekbar.setMax(255);
            if (lampFrequency != 0) {
                mSeekbar.setProgress(lampFrequency);
            } else {
                mSeekbar.setProgress(127);
            }
        }

        /**
         * seekbar滑动监听
         */
        private class OnSeekBarChangeListenerImp implements
                SeekBar.OnSeekBarChangeListener {

            // 触发操作，拖动
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //                setMoveTextLayout();
            }

            // 开始拖动时候触发的操作
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            // 停止拖动时候
            public void onStopTrackingTouch(SeekBar seekBar) {
                rateProgress = seekBar.getProgress();
                //                ConcurrentHashMap<String, Object> dataMap = new ConcurrentHashMap<>();
                //                dataMap.put("LampFrequency", progress);
                //                mDevice.write(dataMap, 0);
            }
        }

        /**
         * seekbar滑动过程中改变moveTextView的位置
         */
        private void setMoveTextLayout() {
            if (mPaint == null) {
                mPaint = new TextPaint();
            }

            float measureText = mPaint.measureText(moveText.getText().toString().trim());
            Rect bounds = mSeekbar.getProgressDrawable().getBounds();
            int xFloat = (int) (bounds.width() * mSeekbar.getProgress() / mSeekbar.getMax() - measureText / 2 + DensityUtil.px2dip(mContext, mLeftMargin));
            if (firstIn) {
                firstIn = false;
                moveText.layout(624, 20, screenWidth, 80);
                moveText.setText(100 + "");
                mTvMax.setText(100 + "");
            } else {
                moveText.layout(xFloat, 20, screenWidth, 80);
                moveText.setText(mSeekbar.getProgress() + "");
                mTvMax.setText(mSeekbar.getProgress() + "");
            }

        }
    }
}
